using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Services
{
    /// <summary>
    /// 内存缓存服务实现
    /// 基于.NET内存缓存的缓存服务实现，提供键值对存储功能
    /// </summary>
    public class CacheService : ICacheService
    {
        /// <summary>
        /// 内存缓存实例
        /// </summary>
        private readonly IMemoryCache _memoryCache;
        
        /// <summary>
        /// 配置对象
        /// </summary>
        private readonly IConfiguration _config;
        
        /// <summary>
        /// 初始化内存缓存服务实例
        /// </summary>
        /// <param name="memoryCache">内存缓存实例</param>
        /// <param name="config">配置对象</param>
        public CacheService(IMemoryCache memoryCache, IConfiguration config)
        {
            _memoryCache = memoryCache;
            _config = config;
        }
        
        /// <summary>
        /// 异步设置缓存项
        /// </summary>
        /// <typeparam name="T">缓存值的类型</typeparam>
        /// <param name="key">缓存键</param>
        /// <param name="value">缓存值</param>
        /// <param name="ttl">过期时间，默认30分钟</param>
        /// <returns>设置操作的异步任务</returns>
        public Task SetAsync<T>(string key, T value, TimeSpan? ttl = null)
        {
            _memoryCache.Set(key, value, ttl ?? TimeSpan.FromMinutes(30));
            return Task.CompletedTask;
        }
        
        /// <summary>
        /// 异步获取缓存项
        /// </summary>
        /// <typeparam name="T">缓存值的类型</typeparam>
        /// <param name="key">缓存键</param>
        /// <returns>缓存值，如果不存在则返回默认值</returns>
        public Task<T?> GetAsync<T>(string key)
        {
            if (_memoryCache.TryGetValue(key, out var value) && value is T tValue)
                return Task.FromResult<T?>(tValue);
            return Task.FromResult<T?>(default);
        }
        
        /// <summary>
        /// 异步移除缓存项
        /// </summary>
        /// <param name="key">要移除的缓存键</param>
        /// <returns>移除操作的异步任务</returns>
        public Task RemoveAsync(string key)
        {
            _memoryCache.Remove(key);
            return Task.CompletedTask;
        }
    }
}
